package com.ftl.search.common.utils;

import com.ftl.search.common.property.JwtProperties;
import com.ftl.search.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class JwtTokenProvider {

    private static final String ROLES = "roles";
    private static final String USERNAME = "username";
    private static final String TYPE = "type";
    private static final String OWNER = "owner";
    private static final String LANGUAGE = "language";
    private static final String GROUP = "group";

    @Resource
    private JwtProperties jwtProperties;

    public User resolveToken(String token) {
        /*
        版本三：最新版本，采用 owner 和 group 代表客户名称，type为client 代表为客户
            {
              "sub": "135",
              "roles": "ROLE_CLIENT",
              "username": "SFI",
              "type": "CLIENT",
              "group": "SFI",
              "owner": "SFI",
              "language": "cn",
              "version": "v1.0",
              "tokenType": "CLIENT",
              "app": "**",
              "jti": "**"
            }
         */
        Claims claims = Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody();
        String id = claims.getSubject();
        String username = get(claims, USERNAME);
        String roles = get(claims, ROLES);
        String type = get(claims, TYPE);
        String owner = get(claims, OWNER);
        String language = get(claims, LANGUAGE);
        String group = get(claims, GROUP);
        return new User(id, username, roles, type, owner, group, language);
    }

    private String get(Claims claims, String key) {
        Object object = claims.get(key);
        if (object == null) {
            return null;
        }
        return object.toString();
    }
}
